package com.application.Activity;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.application.Adapter.RoleAdapter;
import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.DTO.RoleDTO;
import com.application.Network.Protocol;
import com.application.RowDTO.RoleRowDTO;
import com.application.outdoor.InvoikeServices.CommonInvoike;
import com.application.outdoor.InvoikeServices.LogThaoTacInvoike;
import com.application.outdoor.pojo.LogUtil;

public class frmSetRoleActivity extends Activity {
	String path = ReadWriteFileController.ROLE_SETTING_PATH;
	Button btnHoanTat;
	TextView txtTitle;
	ListView lvDanhSachVaiTro;
	ArrayList<RoleDTO> roleList;
	ArrayList<RoleRowDTO> data;
	String ip, name, nguoiDung;
	int flag=1;//=0 nếu cài đặt trước khi tạo nhóm, =1 nếu cài đặt sau khi tạo nhóm
	@Override
	public void onCreate(Bundle savedInstanceState) {
		frmNhomChoActivity.isFirstStart = false;
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.layout_set_role);
		txtTitle = (TextView) findViewById(R.id.txtTitle);
		btnHoanTat = (Button) findViewById(R.id.btnHoanTat);
		lvDanhSachVaiTro = (ListView) findViewById(R.id.lvDanhSachVaiTro);
		lvDanhSachVaiTro.setChoiceMode(2);
		
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			name = bundle.getString(frmNhomChoActivity.NAME_CODE);
			ip = bundle.getString(frmNhomChoActivity.IP_CODE);
			nguoiDung = bundle.getString(Protocol.NGUOI_DUNG);
			if(name.equals("###")==false){
				if(NetworkController.isOutDoor()){
					txtTitle.setText("Cài đặt vai trò cho: " + name);
				}else if(NetworkController.isInDoor()){
					txtTitle.setText("Cài đặt vai trò cho: " + name + " / " + ip);
				}
			}
			else
			{
				flag=0;//cai dat vai trò trước khi tạo nhóm
				txtTitle.setText("Lựa chọn vai trò riêng cho nhóm");
			}
		}
		
		fillListView();

		btnHoanTat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ArrayList<RoleDTO> checkedRoleList = getCheckedRole();
				if(flag==1){//cai dat sau khi tao nhom
					if (checkedRoleList.size() == 0) {
						showErrorAlert("Bạn phải chọn ít nhất 1 vai trò!");
						//return;
					}else{
						if (NetworkController.isInDoor()) {
							
							NetworkController.sendSetRole(new Address(ip), checkedRoleList);
						} else if (NetworkController.isOutDoor()) {
							String noiDung = RoleDTO.toStringList(checkedRoleList);
							try {
								new CommonInvoike().guiTinNhan(CommonUtilities.nguoiDung.getTenDangNhap(), nguoiDung, noiDung,
										Protocol.SET_ROLE);
								//Ghi log
								new LogThaoTacInvoike().insert(CommonUtilities.nguoiDung.getTenDangNhap(), nguoiDung+"#"+noiDung, CommonUtilities.idCayHienTai, LogUtil.DAT_VAI_TRO);
		
							} catch (Exception e) {
								MESApplication.showDialog(frmSetRoleActivity.this, "Lỗi",
										"Không thể đặt vai trò\r\n" + e.getMessage());
							}
						}
					}
				}
				else{//cai dat truoc khi tao nhom
					ReadWriteFileController.writeRole(ReadWriteFileController.ROLE_SETTING_PATH,checkedRoleList);
				}
				finish();
			}
		});

		
	}

	void fillListView() {

		if (!ReadWriteFileController.isFile(path)) {
			roleList = ReadWriteFileController.readRole(getBaseContext(), ReadWriteFileController.ROLE_DEFAULT_PATH);
			ReadWriteFileController.writeRole(path, roleList);
		}else{
			roleList=ReadWriteFileController.readRole(null,path);
		}
		data = new ArrayList<RoleRowDTO>();

		for (RoleDTO role : roleList) {
			RoleRowDTO row = new RoleRowDTO();
			row.role = role;
			row.checked = false;
			data.add(row);
		}
		RoleAdapter adapter = new RoleAdapter(this, data);
		lvDanhSachVaiTro.setAdapter(adapter);

	}

	public int countSelectItem() {
		int n = data.size();
		int count = 0;
		for (int i = 0; i < n; i++) {
			if (data.get(i).checked)
				count++;
		}
		return count;

	}

	private ArrayList<RoleDTO> getCheckedRole() {
		ArrayList<RoleDTO> roleList = new ArrayList<RoleDTO>();
		for (int i = 0; i < data.size(); i++) {
			if (data.get(i).checked)
				roleList.add(data.get(i).role);
		}
		return roleList;
	}

	private void showErrorAlert(String text) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Thông báo");
		alert.setIcon(R.drawable.alerts_error);
		alert.setMessage(text);
		alert.setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				return;
			}
		});
		alert.show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, 1, Menu.NONE, "Quản lý vai trò").setIcon(R.drawable.quan_ly_role);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == 1) {
			Intent intent = new Intent(getBaseContext(), frmQuanLyRoleActivity.class);
			startActivity(intent);
		}
		return true;
	}

	@Override
	public void onResume() {
		super.onResume();
		Log.d("Phu", "onResume frmSetRoleActivity");
		ActivityController.setPeerActivity(this);
		fillListView();
	}

	@Override
	public void onStart() {
		super.onStart();
		ActivityController.setPeerActivity(this);
		ActivityController.addActivityToArray(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		ActivityController.setPeerActivity(this);
	}
}
